var dada=0;
$(function () {
    findBytatus();
    addUsercoupon();
})


//获取所有未过期的优惠券
function findBytatus(){
    $.ajax({
        headers:{
          token: getCookie("token")
        },
        type: "post",
        url: "http://cn.pn.com/api-pn/base/Coupon/v/findAllCoupon",
        dateType:"json",
        async:false,
        success: function (data) {
            $.each(data,function(i,e){
                var startTime=formatDate(new Date(e.startTime));
                var endTime=formatDate(new Date(e.endTime));
                $("#couponlist").append("<div class='bottom layui-col-xs4 layui-col-sm4 layui-row-md4'>\n" +
                    "<div class='yhj'>\n" +
                    "<div class='yhj_l'>\n" +
                    "<small>￥</small>"+e.couponValue+"\n" +
                    "</div>\n" +
                    "<div class='yhj_r\'>\n" +
                    "<div class='yhj_r_t'>\n" +
                    "<div class='d'> "+e.couponName+"</div>\n" +
                    "<div class='x'></div>\n" +
                    "</div>\n" +
                    "<div class='yhj_r_b layui-col-md8'>\n" +
                    "有效期："+startTime+" - "+endTime+"\n" +
                    "</div>\n" +
                    "<div id='couponId' style='display: none'>"+e.couponId+"</div>\n" +
                    "<input type='button' value='20积分领取' class='layui-btn layui-btn-sm layui-btn-danger layui-col-md4 add'>\n" +
                    "</div>\n" +
                    "</div>\n" +
                    "</div>")
            })
        }
    })
}

//通过用户id和优惠券id给用户添加优惠券
function addUsercoupon() {
    $(".add").click(function () {
        //获取优惠券id
        var couponId = ($(this).prev().text())
        $.ajax({
            headers: {
                token: getCookie("token")
            },
            type: "post",
            url: "http://cn.pn.com/api-pn/user/Coupon/v/addUsercoupon",
            data: {couponId: couponId},
            dateType: "json",
            async: false,
            success: function (data) {
                dada=data;
                if (data != 0) {
                    layer.msg("领取成功!")
                    return
                } else {
                    layer.msg("积分不足20无法领取!!!!")
                    return
                }
            }


        })
        if(dada!=0){
            $(this).css('background', '#555');
            $(this).attr({"disabled": true});
            $(this).val("已领取");
        }
    })
}
    function formatDate(now) {
        var year=now.getFullYear();
        var month=now.getMonth()+1;
        var date=now.getDate();
    /*    var hour=now.getHours();
        var minute=now.getMinutes();
        var second=now.getSeconds();*/
    return year+"-"+month+"-"+date/*+" "+hour+":"+minute+":"+second*/;
}
